package com.shao.channelHandler.handler;

import com.shao.Configuration;
import com.shao.SrpcBootstrap;
import com.shao.compress.Compressor;
import com.shao.compress.CompressorFactory;
import com.shao.serialize.Serializer;
import com.shao.serialize.SerializerFactory;
import com.shao.transport.constant.MessageFormatConstant;
import com.shao.transport.message.SrpcResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义响应协议编码器
 * 4B magic(魔数)--->srpc.getBytes()
 * 1B version(版本)----> 1
 * 2B headLength 头部的长度
 * 4B fullLength 报文总长度
 * 1B serialize
 * 1B compress
 * 1B requestType
 * 8B requestId
 * body
 *
 * @author PaoFu
 * @version 1.0
 * @data 2025/4/17 16:06
 */
@Slf4j
public class SrpcResponseEncoder extends MessageToByteEncoder<SrpcResponse> {

    private final Configuration configuration = SrpcBootstrap.getInstance().getConfiguration();

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, SrpcResponse srpcResponse, ByteBuf byteBuf) {
        // 4个字节的魔数值
        byteBuf.writeBytes(MessageFormatConstant.MAGIC);
        // 1个字节的版本号
        byteBuf.writeByte(MessageFormatConstant.VERSION);
        // 2个字节的头部长度
        byteBuf.writeShort(MessageFormatConstant.HEAD_LENGTH);
        // 总长度
        int bodyLength = srpcResponse.getBody() == null ? 0 : body2Bytes(srpcResponse.getBody()).length;
        byteBuf.writeInt(bodyLength + MessageFormatConstant.HEAD_LENGTH);
        // 3个类型
        byteBuf.writeByte(srpcResponse.getResponseCode());
        byteBuf.writeByte(srpcResponse.getCompressType());
        byteBuf.writeByte(srpcResponse.getSerializeType());
        // 8个字节的请求Id
        byteBuf.writeLong(srpcResponse.getRequestId());
        // 如果不是心跳请求写入body
//        if (srpcRequest.getRequestType() == RequestType.NORMAL_REQUEST.getType()) {
            // 获取请求体的字节数组
            byte[] body2Bytes = body2Bytes(srpcResponse.getBody());

            // 写入请求体(requestPayload)
            byteBuf.writeBytes(body2Bytes);
//        }
        // 重新处理报文的总长度
        int writeIndex = byteBuf.writerIndex();
        byteBuf.writerIndex(writeIndex);
        if (log.isDebugEnabled()) {
            log.debug("响应【{}】完成编码", srpcResponse.getRequestId());
        }
    }

    private byte[] body2Bytes(Object body) {
        Serializer serializer = SerializerFactory.getSerializer(configuration.getSerializeType()).getSerializer();
        byte[] serialize = serializer.serialize(body);
        // 压缩
        Compressor compressor = CompressorFactory.getCompressor(configuration.getCompressType()).getCompressor();
        return compressor.compress(serialize);
    }
}
